import React, { useEffect, useState, Key } from "react";
import { useNavigate } from 'react-router-dom';
// 引入用到的元素
import { Button, Checkbox, Form, Input, Table, Space, Tag, Card, message, Tooltip } from 'antd'
//引入放大镜等图标文件
import { SearchOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons"

import type { ColumnsType } from 'antd/es/table';

// 2.引入api中的请求方法
import { getHosSetListRequest, deleteHosSetFromIdRequest, batchDeleteHosRequest, } from '@api/hospital/hospitalSet'

//引入类型
import type { getHosSetListRecordsType, getHosSetListItemsType } from '@/api/hospital/model/hospitalSetTypes'
import type { searchHosFinishPraType } from './types'

//引入样式文件
// import "./index.css"
import style from './index.module.css'


export default function HospitalSet() {
    //使用编程式路由导航hook
    const navigate = useNavigate()

    const [tableData, setTableData] = useState<getHosSetListRecordsType>([])
    const [current, setCurrent] = useState(1)
    const [total, setTotal] = useState(0)
    const [pageSize, setPageSize] = useState(5)
    //定义isLoading(table是否加载中)
    const [isLoading, setIsLoading] = useState(false);
    //定义一个state,专门用来触发useEffect的执行,重新加载
    const [reRender, setReRender] = useState(true)
    //定义一个控制批量删除按钮的一个状态
    const [isSelect, setIsSelecte] = useState(true);
    //定义一个 保存批量选中的ids的状态
    const [bacthSelectIds, setBatchSelectIds] = useState<Key[]>([]);

    const [fieldValue, setFieldValue] = useState<searchHosFinishPraType>({})
    //1,但组件加载时,开始请求分页列表数据
    useEffect(() => {
        //在请求开始之前,设置isLoading为true
        setIsLoading(true)
        //封装一个请求函数才可以,记得后续调用
        const getHosSetList = async () => {
            const result = await getHosSetListRequest({
                page: current,
                limit: pageSize,
                ...fieldValue
            });
            console.log(result, "result");
            //1.把得到的结果中records数据(医院列表的数组)设置给state
            setTableData(result.records)
            //2.把得到的结果中 数据的总长度设置给state
            setTotal(result.total)

            //请求完成后要把isLoading修改为false 
            setIsLoading(false)
        }
        getHosSetList();
    }, [current, pageSize, fieldValue, reRender])

    const columns = [
        {
            title: '序号',
            dataIndex: 'name',
            render(_: any, __: any, index: number) {
                return index + 1
            }
        },
        {
            title: '医院名称',
            dataIndex: 'hosname',
        },
        {
            title: '医院编号',
            dataIndex: 'hoscode',
        },
        {
            title: 'api基础路径',
            dataIndex: 'apiUrl',
        },
        {
            title: '签名',
            dataIndex: 'signKey',
        },
        {
            title: '联系人姓名',
            dataIndex: 'contactsName',
        },
        {
            title: '联系人手机',
            dataIndex: 'contactsPhone',
        },
        {
            title: '操作',
            width: 120,
            fixed: "right" as "right",
            dataIndex: "do",
            render(_: any, data: getHosSetListItemsType) {
                const { id } = data;
                return (
                    <div>
                        <Tooltip title="修改医院">
                            <Button
                                type='primary'
                                icon={<EditOutlined />}
                                className={style.mr}
                                onClick={() => { navigate(`/syt/hospital/updatehosset/${id}`) }}
                            ></Button>
                        </Tooltip>
                        <Tooltip title="删除医院">
                            <Button
                                type='primary'
                                danger
                                icon={<DeleteOutlined />}
                                onClick={deleteHosHandle(id)}
                            ></Button>
                        </Tooltip>
                    </div >
                )
            }
        }

    ];

    //事件回调函数
    //1.点击页码以后的事件回调函数
    const pageChangeHandle = (current: number, pageSize: number) => {
        setCurrent(current)
        setPageSize(pageSize)
    }
    //2.点击查询函数
    const searchHosFinishHandle = (FieldValue: searchHosFinishPraType) => {
        setFieldValue(FieldValue)
    }


    //3.添加医院事件回调函数
    const addHosHandle = () => {
        //编程式路由导航跳转
        navigate("/syt/hospital/addhosset")
    }

    //4.删除单个医院的事件回调函数
    const deleteHosHandle = (id: number) => {
        return async () => {//调用删除的接口
            await deleteHosSetFromIdRequest(id)
            //重新渲染
            setReRender(!reRender)

            message.success("删除医院成功")
        }
    }

    //5.批量删除按钮事件回调函数
    const batchDeleteHandle = async () => {
        //发送批量删除请求
        await batchDeleteHosRequest(bacthSelectIds)

        message.success("批量删除成功");

        //重新渲染
        setReRender(!reRender)

        //把批量删除按钮恢复
        setIsSelecte(true)

    }


    return (
        <div className={style.outer}>
            <Card>
                <Form
                    name="basic"
                    wrapperCol={{ span: 30 }}
                    layout='inline'
                    onFinish={searchHosFinishHandle}
                >
                    <Form.Item
                        name="hosname"
                    >
                        <Input placeholder="医院名称" />
                    </Form.Item>

                    <Form.Item
                        name="hoscode"
                    >
                        <Input placeholder='医院编号' />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                            查询
                        </Button>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="default" htmlType="reset">
                            清空
                        </Button>
                    </Form.Item>
                </Form>
                <div className={style.mt}>
                    <Button type='primary' className={style.mr} onClick={addHosHandle}>添加</Button>
                    <Button onClick={batchDeleteHandle} type="primary" danger disabled={isSelect}>批量删除</Button>
                </div>

                <Table
                    className={style.mt}
                    columns={columns}
                    dataSource={tableData}
                    scroll={{ x: 1100 }}
                    bordered
                    //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
                    rowKey="id"
                    loading={isLoading}
                    rowSelection={{  //小选框属性
                        onChange(ids: Key[]) {   //可以接收两个参数,第一个就是每一条数据所对应的id,第二个就是每一条数据的内容data
                            //设置控制批量删除按钮state的状态
                            setIsSelecte(!ids.length)

                            //当选项框被修改的时候,实时的修改保存所有被选中id的状态
                            setBatchSelectIds(ids);
                        }
                    }}
                    pagination={{
                        //页码的配置：当前页码
                        current,
                        //总数据的数量
                        total,
                        //每页条数
                        pageSize,
                        //展示更改每页条数的选项(默认total大于50条的时候开启)
                        pageSizeOptions: [3, 5, 8, 15],
                        //是否直接开启更新每页条数的选项
                        showSizeChanger: true,

                        showTotal(total) {
                            return `总共有${total}条数据`
                        },

                        onChange: pageChangeHandle

                    }}
                />
            </Card>
        </div>
    )
}


//css的module模块
//1.文件名改为index.module.css
//2.修改引入css样式的方式
//3.改变类名设置{style.mt} ,{style.mr}